package edu.gatech.stolen.tea;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {

	public static final String TAG = "Login Page";

	private Button logInButton;
	private Button registerButton;
	private EditText username;
	private EditText password;
	private TextView loginInfo;
	protected User yourUser;

	/**
	 * Called when the activity is first created. initialize all the buttons and
	 * text fields and labels
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		Log.v(TAG, "Activity State: onCreate()");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		logInButton = (Button) findViewById(R.id.bLoginButton_main);
		registerButton = (Button) findViewById(R.id.bRegisterButton_main);
		username = (EditText) findViewById(R.id.eUsernameEditText_main);
		password = (EditText) findViewById(R.id.ePasswordEditText_main);
		loginInfo = (TextView) findViewById(R.id.lblLoginInfo);

		/**
		 * give log in button a click listener
		 */
		logInButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				onLogInButtonClicked();

			}
		});

		/**
		 * give register button a click listener
		 */
		registerButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				onRegisterButtonClicked();

			}
		});

	}

	/**
	 * when login button is clicked, check for correct login information
	 */
	private void onLogInButtonClicked() {

		Log.v(TAG, "Login Button Clicked");
		checkLogin();

	}

	/**
	 * when register button is clicked go to the register page
	 */
	private void onRegisterButtonClicked() {

		Log.v(TAG, "Register Button Clicked");
		goToRegisterPage();

	}

	/**
	 * get the username and password from the textfields if login successful, go
	 * to login successful page if not then notify the user
	 */
	protected void checkLogin() {

		String user = username.getText().toString();
		String pass = password.getText().toString();

		if (UserManager.login(user, pass)) {
			ItemManager.setUser(UserManager.getUser(user));
			goToItemDisplayListPage();
			finish();
		} else {
			loginInfo.setText("Login failed. Check username or password.");
		}

	}

	/**
	 * go to register page
	 */
	protected void goToRegisterPage() {

		Intent i = new Intent(this, RegisterActivity.class);
		startActivity(i);

	}

	/**
	 * go to successful login page
	 */
	protected void goToItemDisplayListPage() {

		Intent i = new Intent(this, ItemDisplayListActivity.class);
		startActivity(i);

	}

}